/**
 * 活动管理管理页面js
 * 版权所有：上海戈品投资管理有限公司
 *   author king
     功能说明：活动管理
     创建日期：2015-10-19
     修改记录：
     备注说明：
 */

$(document).ready(function() {
	adActiveList();
	 $(".date").datepicker({
	        todayBtn: "linked",
	        keyboardNavigation: false,
	        forceParse: false,
	        calendarWeeks: true,
	        autoclose: true
	    });
});


/**
 * 查询活动列表
 * @returns
 */
var adActiveList = function(){
	 var operTime=$("#operTime").val();
	 var projectName = $("#projectName").val();
	 var userName = $("#userName").val();
	 var phone = $("#phone").val();
	 var status = $("#status").val();
	 
	var datas =  {"p":"adActiveManage","m":"findActiveListPaged","operTime":operTime,"projectName":projectName,"userName":userName,"phone":phone,"status":status};
	var columnDefine = {"id":"编号","operTime":"操作时间","projectName":"项目","projectId":"项目ID","userName":"用户","phone":"手机","status":"状态"};
	
	var formatters={
	            "operTime": function (column, rowData)
	            {
       				var newTime= new Date(rowData.operTime);
       				var rowText=newTime.getFullYear()+'-'+getTheSureTime((newTime.getMonth()+1))+'-'
       				+getTheSureTime(newTime.getDate())+' '+getTheSureTime(newTime.getHours())+':'
       				+getTheSureTime(newTime.getMinutes())+':'+getTheSureTime(newTime.getSeconds());
       				return rowText;
	            },
	            "status": function (column, rowData)
	            {
	   				if(rowData.status=="1")
	   				{
	   					return '<font >未核对</font>';
	   				}
	   				else if(rowData.status=="2")
	   				{
	   					return '<font color="green">已核对</font>';
	   				}
	   				else if(rowData.status=="3")
	   				{
	   					return '<font color="blue">已发放红包</font>';
	   				}
	   				else if(rowData.status=="4")
	   				{
	   					return '<font color="red">异常</font>';
	   				}
	   				else if(rowData.status=="5")
	   				{
	   					return '<font color="blue">伪发红包完成</font>';
	   				}else{
	   					return "";
	   				}
	            }
	 };
	 var buttons =''; //操作按钮
		buttons+='<p>';
		buttons+='<button type=\'button\' class=\'btn btn-w-m btn-primary\' onclick="showEditWin();">编辑</button>&nbsp;&nbsp;';
		buttons+='<button type=\'button\' class=\'btn btn-w-m btn-danger\' onclick="sendRedPack(true);">发放红包</button>&nbsp;&nbsp;';
		buttons+='<button type=\'button\' class=\'btn btn-w-m btn-danger\' onclick="sendRedPack(false);">伪发放红包（只消耗兑换码）</button>&nbsp;&nbsp;';
		buttons+='</p>';
	   hui.pager('service',datas ,"dataList", columnDefine , formatters , buttons ); //分页查询
	
};

var getTheSureTime=function(emp){
	return emp>9?emp:"0"+emp;
};

/**
 * 显示编辑窗口
 */
var showEditWin = function(){
	var data = $('#pop_win .data').text();
	var json = eval('('+data+')');
	
	$('#pop_win').modal('hide');
	$('#editWin input').val('');
	$('#editWin .id').val(json.id);
	$('#editWin .projectName').val(json.projectName);
	$('#editWin .userName').val(json.userName);
	$('#editWin .status').val(json.status);
	$('#editWin .redPackMoney').val(json.redPackMoney);
	$('#editWin').modal('show');
};

/**
 * 显示批量修改状态窗口
 * @returns
 */
var showModifyActiveStatusWin = function(){
	var ids="";
	var checks=$('input[name="select"]:checked');
	if( checks.length==0)
	{
		common.showMsg('error', '' , '请选择至少一条数据！');
		return;
	}
	$('#modifyActiveStatusWin input').val('');
	$('#modifyActiveStatusWin').modal('show');
};

/**
 * 修改状态
 * @returns
 */
var modifyActiveStatus = function(){
	
	var ids='';
	var checks=$('input[name="select"]:checked');
	if( checks.length==0)
	{
		common.showMsg('error', '' , '请选择至少一条数据！');
		return;
	}
	
	$(checks).each(function(){
		if($(this).val()!='all')
		{
			ids+=$(this).val()+',';
		}
	});
	
	if(ids!=''&&ids.indexOf(',')>0)
	{
		ids = ids.substring(0, ids.lastIndexOf(','));
	}	
	var status = $('#modifyActiveStatusWin .status').val();
	var datas = {"p":"adActiveManage","m":"modifyActiveStatus","ids":ids,"status":status};
	var json = common.ajaxRequest('service',datas,'POST');
	if( json && json.result == 0 )
	{
		adActiveList();
		$('#modifyActiveStatusWin').modal('hide');
		common.showMsg('info', '', '修改成功!');
	}
	else
	{
		common.showMsg('error', '', '修改失败!');
		return;
	}	
};

/**
 * 编辑活动状态
 */
var editActive = function(){
	
	var id = $('#editWin .id').val();
	var status = $('#editWin .status').val();
	var datas = {"p":"adActiveManage","m":"modifyActive","id":id,"status":status};
	var json = common.ajaxRequest('service',datas,'POST');
	if( json && json.result == 0 )
	{
		adActiveList();
		$('#editWin').modal('hide');
		common.showMsg('info', '', '修改成功!');
	}
	else
	{
		common.showMsg('error', '', '修改失败!');
		return;
	}	
};

/**
 * 发放红包
 */
var sendRedPack = function(flag){
	var dataStr=$("#pop_win .data").html();
	var data=eval('('+dataStr+')');
	if(sendRedPackRequest(data.id+"",flag)){
		adActiveList();
	}
};

/**
 * 批量发放红包
 */
var sendRedPackBatch = function(flag){
	var idsDom=$("#dataList input[name='select']:checked");
	var adActiveIds="";
	if(idsDom.length<1){
		common.showMsg('error', '', '发红包，至少要选择一条记录');
		return;
	}else if(idsDom.length==1){
		adActiveIds=idsDom.val();
	}else{
		if(idsDom.eq(0).val()!="all"){
			adActiveIds+=idsDom.eq(0).val()+",";
		}
		for(var i=1;i<idsDom.length;i++){
			adActiveIds+=idsDom.eq(i).val()+",";
		}
		adActiveIds=adActiveIds.substring(0, adActiveIds.length-1);
	}
	if(sendRedPackRequest(adActiveIds,flag)){
		//window.location.reload();
		adActiveList();
	}
	
};
/**
 * 发红包请求
 */
var sendRedPackRequest=function(adActiveIds,isSendrp){
	var ld=$("#dataList").attr("ld");
	var issendRp="no";
	if(isSendrp){
		issendRp="yes";
	}
	if(ld=="1"){
		common.showMsg('error', '', '红包正在发放中。。。!');
		return false;
	}
	$("#dataList").attr("ld",1);
	var datas = {"p":"adActiveManage","m":"sendRedPackBatch","adActiveIds":adActiveIds,"isSendRedPack":issendRp};
	var json = common.ajaxRequest('service',datas,'POST');
	if( json )
	{
		//alert(JSON.stringify(json));
		$("#dataList").attr("ld",0);
		var sendResults=json.sendResult;
		sendRedPackReponse(adActiveIds,sendResults);
		if(json.result == 0){
			return true;
		}else{
			//sendRedPackReponse(adActiveIds,sendResults);
			return false;
		}
		
	}else{
		$("#dataList").attr("ld",0);
		common.showMsg('error', '', '操作失败!');
	}
	
};
/**
 * 处理发红包请求后的结果
 */
var sendRedPackReponse=function(adActiveIds,sendResult){
	var results=sendResult.split("||");
	var ids=adActiveIds.split(",");
	var rs="";
	var adR;
	for(var i=0;i<results.length-1;i++){
		adR=results[i].split("_");
		rs+="<p style='color:#FFFFFF;background-color:"+levalInfo(adR[0])+"'>编号="+ids[i]+"	的红包发放情况是："+adR[1]+"</p>";
	}
	var noRs="<br><p>以下的项目还没有发送红包，请您继续操作：</p>";
	var flag=false;
	for(var j=results.length-1;j<ids.length;j++){
		noRs+="<p style='color:#FFFFFF;background-color:"+levalInfo(adR[0])+"'>没有发红包的项目编号：	"+ids[j]+"</p>";
		flag=true;
	}
	if(flag){
		rs+=noRs;
	}
	$("#winOfSureText").html(rs);
	$("#myModalLabel").html("红包发放结果");
	$("#winOfCancell").html("确定").prev().remove();
	$("#showWinOfSure").modal("show");
};
/**
 * 发红包返回结果，等级判断
 * @param e
 * @returns
 */
var levalInfo=function(e){
	var color='';
	switch(e){
		case "0"://成功
			color="#18A689";
			break;
		case "1"://不能发红包
			color="#F7A54A";
			break;
		case "2"://发红包失败
			color="#EC4758";
			break;
		case "3"://发红包异常（微信红包接口调用成功）
			color="#BF0000";
			break;
		default :
			color="#FFFFFF";
	}
	return color;
};
/**
 * 显示核对窗口
 */
var showCheckWin = function(){
	$('#checkWin textarea').val('');
	$('#checkWin').modal('show');
};

/**
 * 核对用户
 */
var checkUser = function(){
	var datas = $('#checkWin textarea').val();
	var projectId = $('#checkWin .projectId').val();
	if( projectId==null || projectId == '' )
	{
		return;
	}	
	
	var json = common.ajaxRequest('service',{"p":"adActiveManage","m":"checkUser","datas":datas,"projectId":projectId},'POST');
	if( json && json.result == 0 )
	{
		adActiveList();
		$('#checkWin').modal('hide');
		common.showMsg('info', '', '操作成功!');
	}
	else
	{
		common.showMsg('error', '', '操作失败!');
		return;
	}	
};

/**
 * 导出未核对用户
 * @returns
 */
var exportData = function(){
	var data = {"p":"adActiveManage","m":"exportData"};
	var json = common.ajaxRequest('service', data , 'POST');
	if( json && json.result == 0 )
	{
		window.open(json.excelFile);
	}
	else
	{
		common.showMsg('error', '', '导出失败!');
		return;
	}
};

/**
 * 过滤数据，带星号的数据
 * @returns
 */
var checkData = function(){
	
	var datas = $('#checkWin textarea').val();
	var projectId = $('#checkWin .projectId').val();
	$('#checkWin .errorData').hide();
	
	var json = common.ajaxRequest('service',{"p":"adActiveManage","m":"diffData","datas":datas,"projectId":projectId},'POST');
	if( json && json.result == 0 )
	{
		$('#checkWin textarea').val( json.datas );
		
		if( json.errorPhones && json.errorPhones!='')
		{
			$('#checkWin .errorData').html('需要核对的手机号：<br/>'+json.errorPhones).show();
		}
		else
		{
			$('#checkWin .errorData').hide();
		}	
	}
	else
	{
		common.showMsg('error', '', '比对失败!');
	}
};
